package org.nowcoder.leetcode.stack;

import java.util.Stack;

/**
 * Title  : 20. Valid Parentheses
 * Source : https://leetcode.cn/problems/valid-parentheses/?envType=study-plan-v2&envId=top-interview-150
 * Author : XrazYang
 * Date   : 2023-07-11
 */

public class LeetCode_20 {
    public boolean isValid(String s) {
        Stack<Character> sta = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '(' || c == '[' || c == '{') {
                sta.push(c);
            } else {
                if (sta.isEmpty()) {
                    if (c == ')' || c == ']' || c == '}') {
                        return false;
                    }
                } else {
                    char peek = sta.peek();
                    if ((c == ')' && peek == '(') || (c == ']' && peek == '[') || (c == '}' && peek == '{')) {
                        sta.pop();
                    } else {
                        return false;
                    }
                }
            }
        }
        return sta.isEmpty();
    }
}
